package com.jeesite.modules.stock.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.jeesite.common.io.FileUtils;
import com.jeesite.modules.stock.dto.UserPageAddDTO;
import com.jeesite.modules.stock.dto.UserPageNameUpdateDTO;
import com.jeesite.modules.stock.dto.UserPageStockSearchDTO;
import com.jeesite.modules.stock.dto.UserPageZbConfigDTO;
import com.jeesite.modules.stock.dto.UserStockAddDTO;
import com.jeesite.modules.stock.dto.UserStockDeleteDTO;
import com.jeesite.modules.stock.entity.UserPageEntity;
import com.jeesite.modules.stock.service.UserStocksService;

@RestController
@RequestMapping("${adminPath}/userstocks")
public class UserStocksController {

    @Autowired
    private UserStocksService userStocksService;

    /**
     * 添加自选股
     */
    @PostMapping("addUserStocks")
    public void addUserStocks(@RequestBody UserStockAddDTO userStockAddDTO) {
        userStocksService.addUserStocks(userStockAddDTO.getUserId(),
                userStockAddDTO.getPageNames(),
                userStockAddDTO.getStockCodes());
    }

    /**
     * 获取用户所有分组
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("getUserPages/{userId}")
    public List<UserPageEntity> getUserPages(@PathVariable String userId) {
        return userStocksService.findUserPages(userId);
    }

    /**
     * 根据分组名称获取分组信息
     *
     * @param userId   用户id
     * @param pageName 分组名称
     * @return
     */
    @GetMapping("getUserPage/{userId}/{pageName}")
    public UserPageEntity getUserPage(@PathVariable String userId, @PathVariable String pageName) {
        List<UserPageEntity> list = userStocksService.findUserPages(userId);
        if (list != null && !list.isEmpty()) {
            return list.stream().filter(item -> item.getPageName().equals(pageName)).findFirst().orElse(null);
        }
        return null;
    }

    /**
     * 获取页面所有自选股
     *
     * @return
     */
    @PostMapping("findUserPageStockList")
    public List<Map<String, Object>> findUserPageStockList(@RequestBody UserPageStockSearchDTO dto) {
        return userStocksService.searchUserPageStockList(dto);
    }

    /**
     * 添加新页面
     *
     * @param userPageAddDTO
     */
    @PostMapping("addUserPage")
    public String addUserPage(@RequestBody UserPageAddDTO userPageAddDTO) {
        try {
            userStocksService.addUserPage(userPageAddDTO.getId(), userPageAddDTO.getUserId(), userPageAddDTO.getPageName());
            return "";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    /**
     * 更新分组
     *
     * @param dto
     * @return
     */
    @PostMapping("updateUserPageName")
    public String updateUserPageName(@RequestBody UserPageNameUpdateDTO dto) {
        return userStocksService.updateUserPageName(dto);
    }

    /**
     * 删除自选股
     *
     * @param userStockDeleteDTO 参数
     */
    @PostMapping("deleteUserStock")
    public void deleteUserStock(@RequestBody UserStockDeleteDTO userStockDeleteDTO) {
        userStocksService.deleteUserStock(userStockDeleteDTO.getUserId(),
                userStockDeleteDTO.getPageName(), userStockDeleteDTO.getStockCodes());
    }

    @GetMapping("deleteUserPage/{ids}")
    public void deleteUserPage(@PathVariable String ids) {
        userStocksService.deleteUserPage(ids);
    }

    @GetMapping("stockInUserStock/{userId}/{stockCode}")
    public boolean stockInUserStock(@PathVariable String userId, @PathVariable String stockCode) {
        return userStocksService.stockInUserStock(userId, stockCode);
    }

    /**
     * 保存页面指标配置
     *
     * @param dto
     */
    @PostMapping("saveUserPageZbConfig")
    public void saveUserPageZbConfig(@RequestBody UserPageZbConfigDTO dto) {
        userStocksService.saveUserPageZbConfig(dto);
    }

    /**
     * 导出股票代码
     */
    @GetMapping("exportStocks")
    public void exportStocks(String stocks, String format, HttpServletRequest request, HttpServletResponse response) {
        try {
            // path是指想要下载的文件的路径
            String path = request.getSession().getServletContext().getRealPath("/");
            String fileName = "deecp_"+System.currentTimeMillis() + "."+format;
            File file = new File(path + "/" + fileName);

            String content = "";
            for (String stockCode : stocks.split(",")) {
                content += stockCode + "\n";
            }
            FileUtils.writeToFile(file.getAbsolutePath(), content, false);

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + file.length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
            outputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
